package com.ffzx.commerce.framework.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.spring.ReferenceBean;
import com.alibaba.dubbo.rpc.service.GenericService;

import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

/**
 * DataDictFunction
 * 
 * @author CMM
 *
 * 2016年8月18日 上午10:01:23
 */
@Component("dataDictFunction")
public class DataDictFunction implements TemplateMethodModelEx {
	
	private final static Logger logger = LoggerFactory.getLogger(DataDictFunction.class);
	
	private GenericService dictApiService;
	
	{
		ReferenceBean<GenericService> referenceConfig = new ReferenceBean<GenericService>();
		referenceConfig.setInterface("com.ffzx.basedata.api.service.DictApiService");
		referenceConfig.setGeneric(Boolean.TRUE);
		referenceConfig.setVersion("1.0");
		referenceConfig.setId("genericDataDictFunctionDictApiService");
		SingletonDubboApplication.getInstance().destroyBean(referenceConfig.getId());
		SingletonDubboApplication.getInstance().addReferenceBean(referenceConfig.getId(), referenceConfig);
		dictApiService = (GenericService) SingletonDubboApplication.getInstance().getReferenceObject(referenceConfig.getId());
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Object exec(List arguments) throws TemplateModelException {
		if (CollectionUtils.isEmpty(arguments)) {
			return Collections.emptyList();
		}else{
			// 数据字典
			Object argument = arguments.get(0);
			logger.debug("参数：",String.valueOf(argument));
			
			Map<?, ?> genericResult = (Map<?, ?>) dictApiService.$invoke("getDictByType", new String[] { "java.lang.String" }, new Object[] { String.valueOf(argument) });
			String code = (String)genericResult.get("code");
			String message = (String)genericResult.get("message");
			List<Map> dataList = (List<Map>)genericResult.get("data");
			logger.debug("返回code：", code);
			logger.debug("返回message：", message);
			logger.debug("返回data：", dataList);
			
			List<Map<String, String>> returnList = new ArrayList<Map<String,String>>();
			for(Map dataMap : dataList){
				Map<String, String> dictMap = new HashMap<String, String>();
				dictMap.put("valueStr", String.valueOf(dataMap.get("value")));
				dictMap.put("nameStr", String.valueOf(dataMap.get("label")));
				returnList.add(dictMap);
			}
			
			return returnList;
		}
	}

}
